import CryptoJS from 'crypto-js';
import { Base64 } from "js-base64";
import moment from 'moment';

export default {
  encode(account, password) {
    if (!account || !password) {
      return null;
    }
    let domainIndex = account.indexOf('\\');
    if (domainIndex > 0) {
      account = account.substring(domainIndex + 1);
    }
    if (account.length <= 3) {
      account = this.padZero(account, 4);
    }
    let timeStamp = moment().valueOf();

    //将账号 base64 编码
    let baseUsername = this.base64Encode(account);

    // 将密码加上到秒的时间戳（yyyyMMddHHmmss）作为加密原文
    let cipherText = Object.assign(password).concat(timeStamp);

    //将加密原文使用 MD5 的方式加密，将 MD5 值去除中划线，倒序排列生成 base64 编码，base64 字符对应的 asc码值求和作为校验位
    let md5Text = this.encryptMd5(cipherText).replace(/-/g, '');
    let reverseMd5Text = this.base64Encode(StrUtils.reverse(md5Text));
    let reverseAscSum = StrUtils.strAscSum(reverseMd5Text);
    let key = baseUsername.concat(reverseAscSum);
    //对加密原文使用 DES 方式加密，秘钥为第四生成，生成密文
    let finalCipherText = this.encryptDes(cipherText, key);

    //将密文和校验位使用{密文}#{校验位}的方式拼接字符的 base64 编码字符作为密码
    return this.base64Encode(
      finalCipherText.concat('#').concat(reverseAscSum.toString()),
    );
  },

  padZero(num, n) {
    var len = num.toString().length;
    while (len < n) {
      num = num + '0';
      len++;
    }
    return num;
  },
  base64Encode(code) {
    if (code && code !== '') {
      return Base64.encode(code);
    }
    return '';
  },
  encryptDes(message, key) {
    let keyHex = CryptoJS.enc.Utf8.parse(key);
    let encrypted = CryptoJS.DES.encrypt(message, keyHex, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    return encrypted.toString();
  },
  decryptDes(cipherText, key) {
    let keyHex = CryptoJS.enc.Utf8.parse(key);
    let decrypted = CryptoJS.DES.decrypt(
      {
        ciphertext: CryptoJS.enc.Base64.parse(cipherText),
      },
      keyHex,
      {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      },
    );

    return decrypted.toString(CryptoJS.enc.Utf8);
  },
  encryptMd5(key) {
    return CryptoJS.MD5(key).toString();
  },
};
